import Vue from 'vue'
import Router from 'vue-router'
import { local } from 'me-view/src/index'
Vue.use(Router)

/**
 * 转换为 '-' 替换驼峰命名
 * @param {String} target 路径
 * @param {String} connector 分隔符 默认 -
 */
function formatFile (target, connector = '-') {
  return target.split('/').flatMap(item => {
    const newItem = item.replace(/([A-Z])/g, $1 => connector + $1.toLowerCase())
    return newItem.startsWith('-') ? newItem.replace('-', '') : newItem
  }).join('/')
}

// 动态获取路由： 根据目录结构

const fileExample = require.context('../../example/', true, /.md$|.vue$/).keys()
const filePackage = require.context('../../../packages/', true, /.md$|.vue$/).keys()
const route = []
function parseRoute (target = [], callback = () => {}) {
  return [ target ].flat().flatMap(item => {
    const path = `/demo/${formatFile(item.replace('./', '').replace('/example/', '/').replace(/.md$|.vue$/, ''))}`
    route.push({ path, fullPath: item.replace('./', '') })
    return {
      path,
      component: callback(item.replace('./', ''))
    }
  })
}
const children = [
  ...parseRoute(fileExample, item => () => import('me-view/multiple-page/example/' + item)),
  ...parseRoute(filePackage.filter(item => item.includes('example')), item => () => import('me-view/packages/' + item))
]
local.set('route-demo', route)
export default new Router({
  mode: 'history',
  routes: [
    { path: '/demo', redirect: '/demo/index' },
    ...children
  ]
})
